package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("RulefieldRestController")
public class RulefieldRestController extends CmiEmaController {

	/**
	 * Create a new Rulefield entity
	 * 
	 */
	@RequestMapping(value = "/newRulefield", method = RequestMethod.POST)
	@ResponseBody
	public Object newRulefield(@RequestBody Rulefield rulefield) {
		rulefieldService.saveRulefield(rulefield);
		return JSONObject.parse(cmiPsonService.toJsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefield.getId()), 2));
	}

	@RequestMapping(value = "/restNewRulefield", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewRulefield(@RequestBody String rulefieldJson) {
		Rulefield rulefield = new Gson().fromJson(rulefieldJson, Rulefield.class);
		appendReferences(rulefield);
		rulefieldService.saveRulefield(rulefield);
		return JSONObject.parse(cmiPsonService.toJsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefield.getId()), 2));
	}

	@RequestMapping(value = "/saveRulefield", method = RequestMethod.PUT)
	@ResponseBody
	public Rulefield saveRulefield(@RequestBody Rulefield rulefield) {
		rulefieldService.saveRulefield(rulefield);
		return rulefieldDAO.findRulefieldByPrimaryKey(rulefield.getId());
	}

	@RequestMapping(value = "/restSaveRulefield", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveRulefield(@RequestBody String rulefieldJson) {
		Rulefield rulefield = new Gson().fromJson(rulefieldJson, Rulefield.class);
		appendReferences(rulefield);
		CmiPsonService cmiPsonService = new CmiPsonService();
		rulefieldService.saveRulefield(rulefield);
		return JSONObject.parse(cmiPsonService.toJsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefield.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteRulefield/{rulefieldId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteRulefield(@PathVariable Integer rulefieldId) {
		Rulefield rulefield = rulefieldDAO.findRulefieldByPrimaryKey(rulefieldId);
		rulefieldService.deleteRulefield(rulefield);
	}

	@RequestMapping(value = "/restConfirmDeleteRulefields")
	@ResponseBody
	public Object restConfirmDeleteRulefields(@RequestBody Set<Integer> deleteRulefieldsIds) {
		Set<Rulefield> deleteRulefields = rulefieldDAO.findRulefieldsByIds(deleteRulefieldsIds);
		Set<Rulefield> referencedRulefields = rulefieldService.loadReferenceRulefields(deleteRulefields);
		deleteRulefields.removeAll(referencedRulefields);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedRulefields);
		jsonObject.put("deleteEntitys", deleteRulefields);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteRulefields")
	@ResponseBody
	public Object restDeleteRulefields(@RequestBody Set<Rulefield> deleteRulefields) {
		Iterator<Rulefield> iterator = deleteRulefields.iterator();
		while (iterator.hasNext()) {
			Rulefield currentRulefield = iterator.next();
			rulefieldService.deleteRulefield(currentRulefield);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listRulefields");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadRulefield/{rulefieldId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRulefield(@PathVariable Integer rulefieldId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefieldId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadRulefieldRule/{rulefieldId}/rule", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRulefieldRule(@PathVariable Integer rulefieldId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefieldId).getRule(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadRulefieldRulecolumns/{rulefieldId}/rulecolumns/{relatedrulecolumnId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadRulefieldRulecolumns(@PathVariable Integer rulefieldId,
			@PathVariable Integer relatedrulecolumnId, @RequestBody CmiPagination cmiPagination) {
		Rulecolumn rulecolumn = rulecolumnDAO.findRulecolumnByPrimaryKey(relatedrulecolumnId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(rulecolumn, 2, cmiPagination));
	}

	public void appendReferences(Rulefield rulefield) {

		Rule rule = rulefield.getRule();
		if (rule != null)
			rulefield.setRule(ruleService.findRuleByPrimaryKey(rule.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Rulecolumn> rulecolumnsForRulefield = new HashSet<>();
		for (Rulecolumn rulecolumn_Rulefield : rulefield.getRulecolumnsForRulefield()) {
			rulecolumnsForRulefield.add(rulecolumnService.findRulecolumnByPrimaryKey(rulecolumn_Rulefield.getId()));
		}
		rulefield.setRulecolumnsForRulefield(rulecolumnsForRulefield);
	}

	@RequestMapping(value = "/restGetRulefieldRule/{rulefieldId}/rule", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetRulefieldRule(@PathVariable Integer rulefieldId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(rulefieldDAO.findRulefieldByPrimaryKey(rulefieldId).getRule(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetRulefieldRulecolumns/{rulefieldId}/rulecolumns", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetRulefieldRulecolumns(@PathVariable Integer rulefieldId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				rulefieldDAO.findRulefieldByPrimaryKey(rulefieldId).getRulecolumnsForRulefield(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListRulefields", method = RequestMethod.GET)
	@ResponseBody
	public Object restListRulefields() {
		return JSONObject.parse(cmiPsonService.toJsonString(rulefieldService.loadRulefields(), 2));
	}

	@RequestMapping(value = "/restListRulefieldsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListRulefieldsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = rulefieldPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Rulefield> rulefields = rulefieldDAO.findAllRulefields(startResult, cmiPagination.getPaginationSize());
		String rulefieldString = cmiPsonService.toPsonString(rulefields, 2, cmiPagination);

		return JSONObject.parse(rulefieldString);
	}

	@RequestMapping("/rulefieldSelectBox")
	@ResponseBody
	public JSONObject rulefieldSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Rule":
				entitySet = ruleService.loadRulesByIdSet(searchValue);
				break;

			// 被引用键
			case "Rulecolumn":
				entitySet = rulecolumnService.loadRulecolumnsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Rule":
				entitySet = ruleDAO.findAllRules((pageNumber - 1) * paginationSize, paginationSize);
				count = ruleService.countRules();
				break;

			// 被引用键
			case "Rulecolumn":
				entitySet = rulecolumnDAO.findAllRulecolumns((pageNumber - 1) * paginationSize, paginationSize);
				count = rulecolumnService.countRulecolumns();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Rule":
				entitySet = ruleDAO.findRuleByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = ruleService.countRulesByName(queryword);
				break;

			// 被引用键
			case "Rulecolumn":
				entitySet = rulecolumnDAO.findRulecolumnByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = rulecolumnService.countRulecolumnsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
